package com.hcms.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hcms.common.Result;
import com.hcms.entity.Association;
import com.hcms.entity.User;
import com.hcms.mapper.AssociationMapper;
import com.hcms.mapper.UserMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/association")
public class AssociationController {

    @Resource
    AssociationMapper associationMapper;
    @Resource
    UserMapper userMapper;

    @PostMapping
    public Result<?> save(@RequestBody Association association){
        associationMapper.insert(association);
        return Result.success();
    }

    @PutMapping
    public Result<?> update(@RequestBody Association association){
        associationMapper.updateById(association);
        return Result.success();
    }

    @DeleteMapping("/{id}") //删除
    public Result<?> update(@PathVariable Long id){
        Integer a = associationMapper.deleteById(id);
        System.out.println(a);
        return Result.success();
    }

    @PutMapping("/{id}") //加入社团
    public Result<?> add(@PathVariable Integer id,HttpSession session){
        Integer userId = (Integer) session.getAttribute("userId");
        userMapper.update(id,userId);
        return Result.success();
    }


    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search){
        LambdaQueryWrapper<Association> wrapper = Wrappers.<Association>lambdaQuery();
        if (StrUtil.isNotBlank(search))
        {
             wrapper.like(Association::getName, search);
        }
        Page<Association> AssociationPage = associationMapper.selectPage(new Page<>(pageNum,pageSize),wrapper);
        return Result.success(AssociationPage);
    }

}
